package com.android.jay.lib_network.okhttp.response;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.android.jay.lib_network.okhttp.exception.OkHttpException;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataHandler;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by wzp on 2019/12/28 0028.
 * <p>
 * 描述  ：处理json类型的响应
 */
public class CommonJsonCallback implements Callback {

    protected final String EMPTY_MSG = "";
    protected final int NETWORK_ERROR = -1;
    protected final int JSON_ERROR = -2;
    protected final int OTHER_ERROR = -3;
    private DisposeDataListener mListener;
    private Class<?> mClass;
    //将回传回来的子线程 传到主线程中的handler
    private Handler mDeliveryHandler;

    public CommonJsonCallback(DisposeDataHandler handler) {
        this.mListener = handler.mListener;
        this.mClass = handler.mClass;
        this.mDeliveryHandler = new Handler(Looper.getMainLooper());
    }


    @Override
    public void onFailure(@NotNull Call call, @NotNull final IOException e) {
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                Log.e("wzp -=-=-===", "result ==== " + e.getMessage());
                mListener.onFailure(new OkHttpException(NETWORK_ERROR, e));
            }
        });
    }

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

        final String result = response.body().string();
        Log.e("wzp -=-=-===", "result ==== " + result);
        mDeliveryHandler.post(new Runnable() {
            @Override
            public void run() {
                handleResponse(result);
            }
        });
    }

    private void handleResponse(String result) {
        if (result == null || result.trim().equals("")) {
            mListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
            return;
        }
        try {
            if (mClass == null) {
                //不需要解析直接传到应用层自己处理
                mListener.onSuccess(result);
            } else {
                //解析成为实体对象
                Object obj = new Gson().fromJson(result, mClass);
                if (obj != null) {
                    mListener.onSuccess(obj);
                } else {
                    mListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
                }
            }
        } catch (Exception e) {
            mListener.onFailure(new OkHttpException(JSON_ERROR, e));
        }
    }
}
